/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.biz.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.excel.ExportCSV;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.modules.biz.entity.*;
import com.thinkgem.jeesite.modules.biz.service.*;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.AutoNameUtils;
import com.thinkgem.jeesite.modules.sys.utils.LogUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 采购单的controllerController
 * @author tiancheng
 * @version 2018-07-13
 */
@Controller
@RequestMapping(value = "${adminPath}/biz/bizPurchase")
public class BizPurchaseController extends BaseController {

	@Autowired
	private BizPurchaseService bizPurchaseService;
	@Autowired
	private BizPurchaseDetailService bizPurchaseDetailService;
	@Autowired
	private BizGoodsService bizGoodsService;
	@Autowired
	private BizStockInService bizStockInService;
	@Autowired
	private BizStockInDetailService bizStockInDetailService;
	@Autowired
	private BizPurchaseLogService bizPurchaseLogService;
	@Autowired
	private BizBuyingRequisitionService bizBuyingRequisitionService;
	@Autowired
	private BizBuyingRequisitionDetailService bizBuyingRequisitionDetailService;


	private static Logger log = LoggerFactory.getLogger(ExportExcel.class);

	@ModelAttribute
	public BizPurchase get(@RequestParam(required=false) String id) {
		BizPurchase entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = bizPurchaseService.get(id);
		}
		if (entity == null){
			entity = new BizPurchase();
		}
		return entity;
	}
	
	@RequiresPermissions("biz:bizPurchase:view")
	@RequestMapping(value = {"list", ""})
	public String list(BizPurchase bizPurchase, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<BizPurchase> page = bizPurchaseService.findPage(new Page<BizPurchase>(request, response), bizPurchase); 
		model.addAttribute("page", page);
		model.addAttribute("type", bizPurchase.getType());
		return "modules/biz/bizPurchaseList";
	}

	@RequiresPermissions("biz:bizPurchase:financeView")
	@RequestMapping(value = "listForFinance")
	public String listForFinance(BizPurchase bizPurchase, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<BizPurchase> page = bizPurchaseService.findPageForFinance(new Page<BizPurchase>(request, response), bizPurchase);
		model.addAttribute("page", page);
		model.addAttribute("type", bizPurchase.getType());
		return "modules/biz/bizPurchaseListForFinance";
	}

	@RequiresPermissions("biz:bizPurchase:view")
	@RequestMapping(value = "form")
	public String form(BizPurchase bizPurchase, Model model, HttpServletRequest request, HttpServletResponse response) {
		model.addAttribute("bizPurchase", bizPurchase);
		BizGoods bizGoods = new BizGoods();
		model.addAttribute("bizGoods",bizGoods );
		if(null != bizPurchase && StringUtils.isNotEmpty(bizPurchase.getPurchaseId())){
			//采购单的明细
			BizPurchaseDetail bizPurchaseDetail = new BizPurchaseDetail();
			bizPurchaseDetail.setPurchaseId(bizPurchase.getPurchaseId());
			List<BizPurchaseDetail> bizPurchaseDetailList = bizPurchaseDetailService.findList(bizPurchaseDetail);
			model.addAttribute("bizPurchaseDetailList",bizPurchaseDetailList);
			model.addAttribute("bizPurchaseDetailCount",bizPurchaseDetailList.size());

			//查询入库单
			BizStockIn bizStockIn = new BizStockIn();
			bizStockIn.setPurchaseId(bizPurchase.getPurchaseId());
			//查询全部的入库单
			List<BizStockIn> bizStockInList = bizStockInService.findList(bizStockIn);
			for (BizStockIn stockIn:bizStockInList) {
				BizStockInDetail bizStockInDetail = new BizStockInDetail();
				bizStockInDetail.setStockInId(stockIn.getStockInId());
				//当前入库单下面的入库单明细
				List<BizStockInDetail> bizStockInDetailList = bizStockInDetailService.findList(bizStockInDetail);
				stockIn.setBizStockInDetailList(bizStockInDetailList);
			}
			model.addAttribute("bizStockInList",bizStockInList);
		}
		return "modules/biz/bizPurchaseInspectionForm";
	}

	@RequiresPermissions("biz:bizPurchase:financeView")
	@RequestMapping(value = "formForFinance")
	public String formForFinance(BizPurchase bizPurchase, Model model, HttpServletRequest request, HttpServletResponse response) {
		model.addAttribute("bizPurchase", bizPurchase);
		BizGoods bizGoods = new BizGoods();
		model.addAttribute("bizGoods",bizGoods );
		if(null != bizPurchase && StringUtils.isNotEmpty(bizPurchase.getPurchaseId())){
			//采购单的明细
			BizPurchaseDetail bizPurchaseDetail = new BizPurchaseDetail();
			bizPurchaseDetail.setPurchaseId(bizPurchase.getPurchaseId());
			List<BizPurchaseDetail> bizPurchaseDetailList = bizPurchaseDetailService.findList(bizPurchaseDetail);
			model.addAttribute("bizPurchaseDetailList",bizPurchaseDetailList);
			model.addAttribute("bizPurchaseDetailCount",bizPurchaseDetailList.size());

			//查询入库单
			BizStockIn bizStockIn = new BizStockIn();
			bizStockIn.setPurchaseId(bizPurchase.getPurchaseId());
			//查询全部的入库单
			List<BizStockIn> bizStockInList = bizStockInService.findList(bizStockIn);
			for (BizStockIn stockIn:bizStockInList) {
				BizStockInDetail bizStockInDetail = new BizStockInDetail();
				bizStockInDetail.setStockInId(stockIn.getStockInId());
				//当前入库单下面的入库单明细
				List<BizStockInDetail> bizStockInDetailList = bizStockInDetailService.findList(bizStockInDetail);
				stockIn.setBizStockInDetailList(bizStockInDetailList);
			}
			model.addAttribute("bizStockInList",bizStockInList);
		}

		return "modules/biz/bizPurchaseFormForFinance";
	}

	@RequiresPermissions(value={"biz:bizPurchase:add","biz:bizPurchase:edit"},logical= Logical.OR)
	@RequestMapping(value = "save")
	public String save(String source, BizPurchase bizPurchase, Model model, RedirectAttributes redirectAttributes,
					   HttpServletRequest request, HttpServletResponse response) {
		if (!beanValidator(model, bizPurchase)){
			return form(bizPurchase, model,request,response);
		}
		String url = "redirect:"+Global.getAdminPath()+"/biz/bizPurchase/list";
		bizPurchaseService.save(bizPurchase);
		addMessage(redirectAttributes, "保存采购单成功");
		return url;
	}
	
	@RequiresPermissions("biz:bizPurchase:remove")
	@RequestMapping(value = "delete")
	public String delete(BizPurchase bizPurchase, RedirectAttributes redirectAttributes) {
		try {
			bizPurchaseService.delete(bizPurchase);
			//删除采购单时，将明细一起删除,并修改商品的库存
			//当前采购单下的采购明细
			BizPurchaseDetail bizPurchaseDetail = new BizPurchaseDetail();
			bizPurchaseDetail.setPurchaseId(bizPurchase.getPurchaseId());
			List<BizPurchaseDetail> bizPurchaseDetailListInfo = bizPurchaseDetailService.findList(bizPurchaseDetail);
			if(null != bizPurchaseDetailListInfo && bizPurchaseDetailListInfo.size() > 0){
				//先把商品的采购数量还原
				for (BizPurchaseDetail purchaseDetail:bizPurchaseDetailListInfo) {
					BizGoods bizGoods = bizGoodsService.get(purchaseDetail.getGoodsId());
					//给商品修改采购数量（删除）
					Integer num = Integer.valueOf(bizGoods.getPurchasingAmount()) - Integer.valueOf(purchaseDetail.getExpertAmount());
					bizGoods.setPurchasingAmount(num.toString());
					bizGoodsService.updateInfo(bizGoods);
				}
				//删除当前采购单下的采购明细
				bizPurchaseDetailService.deleteByPurchaseIdLJ(bizPurchase.getPurchaseId());
			}
		} catch (Exception e) {
			addMessage(redirectAttributes, "删除采购单失败");
			e.printStackTrace();
		}
		addMessage(redirectAttributes, "删除采购单成功");
		return "redirect:"+Global.getAdminPath()+"/biz/bizPurchase/list";
	}


	 /**
	  * 修改采购单的状态
	  * @author tiancheng  
	  * @date 2018/7/16 8:47
	  * @param
	  * @return   
	  */  
	/*@RequestMapping(value = "updateStatus")
	public String updateStatus(BizPurchase bizPurchase, RedirectAttributes redirectAttributes) {
		try {
			//如果是验货，判断采购单下面的采购明细是否全部到货
			if(null != bizPurchase.getStatus() && bizPurchase.getStatus().equals("2")){
				//查询采购单下面的明细是否全部到货
				Integer num = bizPurchaseDetailService.selectByPurchaseIdAndDifferentAmount(bizPurchase.getPurchaseId());
				if(num > 0){
					addMessage(redirectAttributes, "当前采购单下有未全部到货的商品，请及时查看！");
					return "redirect:"+Global.getAdminPath()+"/biz/bizPurchase/list?type="+bizPurchase.getType();
				}
			}
			//添加操作日志
			//bizPurchaseLogService.addBizPurchaseLog(bizPurchase.getStatus(),bizPurchase.getPurchaseId());
			bizPurchaseService.updateStatus(bizPurchase);
			addMessage(redirectAttributes, "执行操作成功！");
		} catch (Exception e) {
			addMessage(redirectAttributes, "执行操作失败！");
			e.printStackTrace();
		}
		return "redirect:"+Global.getAdminPath()+"/biz/bizPurchase/list";
	}*/

	
	 /**
	  * 到货验货时修改采购单的明细
	  * @author tiancheng
	  * @date 2018/7/16 14:00
	  * @param
	  * @return
	  */
	/*@RequestMapping(value = "inspection")
	public String inspection(BizPurchase bizPurchase, RedirectAttributes redirectAttributes) {
		//修改采购单的明细的实际入库数量|
		List<BizPurchaseDetail> bizPurchaseDetailList = bizPurchase.getPurchaseDetailList();
		for (BizPurchaseDetail bizPurchaseDetail:bizPurchaseDetailList){
			//修改采购明细
			if(null != bizPurchaseDetail && null != bizPurchaseDetail.getPurchaseDetailId()){
				//实际入库数量不为空，就修改采购单明细
				if(null != bizPurchaseDetail.getActualAmount()){
					bizPurchaseDetailService.updateAmount(bizPurchaseDetail);
				}
			}
		}
		addMessage(redirectAttributes, "修改采购单成功！");
		return "redirect:"+Global.getAdminPath()+"/biz/bizPurchase/list?type=1";
	}*/

	/**
	 * 采购单平单
	 * @author xuchen
	 * @date 2018/8/30
	 * @param
	 * @return
	 */
	@RequestMapping(value = "flatSheet")
	public String flatSheet(BizPurchase bizPurchase, RedirectAttributes redirectAttributes, String source) {
		String url = "redirect:"+Global.getAdminPath()+"/biz/bizPurchase/list";
		if(bizPurchase != null){
            String purchaseId = bizPurchase.getPurchaseId();
            if(StringUtils.isNotEmpty(purchaseId)){
                if(StringUtils.isNotEmpty(source)){
                    if("form".equals(source)){
                        url = "redirect:"+Global.getAdminPath()+"/biz/bizPurchase/form?id="+bizPurchase.getPurchaseId();
                    }
                }
                //同步入库数量到采购单明细中的采购数量
                BizPurchaseDetail bizPurchaseDetail = new BizPurchaseDetail();
                bizPurchaseDetail.setPurchaseId(purchaseId);
                List<BizPurchaseDetail> bizPurchaseDetailList = bizPurchaseDetailService.findList(bizPurchaseDetail);
                if(bizPurchaseDetailList != null && bizPurchaseDetailList.size() > 0){
                    bizPurchase.setStatus("12");//已完成
					bizPurchase.setFinancialStatus("10");
                    bizPurchaseService.updateStatus(bizPurchase);
                    //添加操作日志
                    bizPurchaseLogService.addBizPurchaseLog("平单",purchaseId);
                    addMessage(redirectAttributes, "平单成功！");
                }else{
                    addMessage(redirectAttributes, "平单失败,请联系管理员！");
                }
            }else{
                addMessage(redirectAttributes, "平单失败,请联系管理员！");
            }
		}
		return url;
	}



	/**
	 * 导出
	 * @author xuchen
	 * @date 2018/11/06 15:10
	 * @param
	 * @return
	 */
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public String exportFile(BizPurchase bizPurchase, HttpServletRequest request,
							 HttpServletResponse response, RedirectAttributes redirectAttributes) {
		// 导出完毕提示的消息
		String msg = "";
		//记录日志操作
		String startOperation="开始进行采购单数据导出操作！";
		String endOperation="采购单数据导出操作结束！";
		User user = UserUtils.getUser();
		try {

			String fileNamePrefix = DateUtils.getDate("yyyyMMddHHmmss");// 导出文件名前缀
			List<String> fileNames = new ArrayList<String>(); // 存放生成的文件名称
			String exportDir = FileUtils.path(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + user.getId()
					+ "/files/exportFiles/" + DateUtils.getDate("yyyy-MM-dd") + "/");
			String filePath = exportDir + fileNamePrefix + "/";// 导出文件子目录
			if (!new File(filePath).exists()) {
				new File(filePath).mkdirs();
			}
			String zipFileName = fileNamePrefix + ".zip";// 压缩文件名称
			String zipFilePath = exportDir + zipFileName;// 压缩文件路径
			// 根据查询条件查询
			Page<BizPurchaseDetail> page = new Page<BizPurchaseDetail>();
			// 需要导出的数据总数目
			int dataSize = 0;
			try {
				// 获取商品列表的导出总条数
				List<BizPurchaseDetail> bizPurchaseDetails = bizPurchaseDetailService.
						findListByParent(bizPurchase);
				dataSize = bizPurchaseDetails.size();
			} catch (Exception e) {
				log.info("获取导出的数据总数目失败！失败信息：" + e.getMessage());
				LogUtils.saveLog(request, null, e, "获取导出的数据总数目失败！");
			}
			if (dataSize == 0) {
				msg = "导出失败！失败信息：导出数据为空";
				addMessage(redirectAttributes, "导出失败！失败信息：导出数据为空");
				log.info("导出失败！失败信息：导出数据为空");
				LogUtils.saveLog(request, user.getName() + "导出失败！失败信息：导出数据为空");
				return "redirect:"+Global.getAdminPath()+"/biz/bizPurchase/?repage";
			} else {// 5000数据分一个文件
				int fileSize = StringUtils.isBlank(Global.getConfig("exportExcel.fileSize")) ? 5000
						: Integer.parseInt(Global.getConfig("exportExcel.fileSize"));
				int fileNo = dataSize / fileSize + 1;
				for (int i = 1; i <= fileNo; i++) {
					page = bizPurchaseDetailService.findPageByParent(
							new Page<BizPurchaseDetail>(i, fileSize),
							bizPurchase);
					String fileName = fileNamePrefix + "-" + String.valueOf(i) + ".csv";
					fileNames.add(fileName);
					// 创建csv文件
					new ExportCSV(BizPurchaseDetail.class, 1).setDataList(page.getList()).writeFile(filePath + fileName);
				}
				System.out.println("需要压缩的文件所在目录：" + filePath);
				System.out.println("压缩文件所在目录：" + exportDir);
				System.out.println("压缩文件名称：" + zipFilePath);

				log.info(startOperation);
				log.info("操作人：" + UserUtils.getUser().getName());
				log.info("预计导出数据共" + dataSize + "条");

				FileUtils.zipFiles(filePath, "", zipFilePath);

				FileUtils.delFile(filePath);
				msg = "导出成功！共导出数据：" + dataSize + "条。" + "文件只保留" + Global.getConfig("userfiles.life") + "天，请尽快到“"
						+ "<a href='" + request.getContextPath() + Global.getAdminPath()
						+ "/../static/ckfinder/ckfinder.html' class='alert-link'>我的面板-文件管理</a>" + "”中下载！";
				addMessage(redirectAttributes,
						"导出成功！共导出数据：" + dataSize + "条。" + "文件只保留" + Global.getConfig("userfiles.life") + "天，请尽快到“"
								+ "<a href='" + request.getContextPath() + Global.getAdminPath()
								+ "/../static/ckfinder/ckfinder.html' style='color: white'>我的面板-文件管理</a>" + "”中下载！");
				log.info(endOperation);
				LogUtils.saveLog(request, user.getName() + "导出信息" + dataSize + "条");
			}
		} catch (Exception e) {
			msg = "导出失败！失败信息：" + e.getMessage();
			addMessage(redirectAttributes, "导出失败！失败信息：" + e.getMessage());
			log.info("导出失败！失败信息：" + e.getMessage());
			LogUtils.saveLog(request, null, e, user.getName() + "导出失败！");
		}
		return "redirect:"+Global.getAdminPath()+"/biz/bizPurchase/list";
	}


	/**
	 * 修改采购单审核状态
	 * @author xuchen
	 * @date 2018/12/03 16:44
	 * @param
	 * @return
	 */
	@RequiresPermissions(value={"biz:bizPurchase:submit","biz:bizPurchase:toExamine",
								"biz:bizPurchase:reject","biz:bizPurchase:resubmit","biz:bizPurchase:withdraw"},logical= Logical.OR)
	@RequestMapping(value = "updateAuditStatus")
	public String updateAuditStatus(BizPurchase bizPurchase,RedirectAttributes redirectAttributes) {


		BizPurchase purchase = bizPurchaseService.get(bizPurchase);	//当前采购单
		List<BizPurchaseDetail> purchaseDetailList = new ArrayList<>();	//当前采购单明细
		if(purchase != null && StringUtils.isNotEmpty(purchase.getPurchaseId())){
			BizPurchaseDetail selectPurDetail = new BizPurchaseDetail();
			selectPurDetail.setPurchaseId(purchase.getPurchaseId());
			purchaseDetailList = bizPurchaseDetailService.findList(selectPurDetail);
		}

		if(bizPurchase != null && StringUtils.isNotEmpty(bizPurchase.getAuditStatus())){
			if("20".equals(bizPurchase.getAuditStatus())){
				boolean isCanSubmit = true;	//是否可以提交当前采购单
				StringBuffer msg = new StringBuffer();	//提示消息
				msg.append("提交失败:");

				for (BizPurchaseDetail bizPurchaseDetail : purchaseDetailList) {
					//根据采购单明细的请购明细id获取该请购明细的请购数和已提交采购数
					if(bizPurchaseDetail != null && StringUtils.isNotEmpty(bizPurchaseDetail.getPurchaseDetailId())){
						String buyingDetailId = bizPurchaseDetail.getBuyingDetailId();
						//获取对应请购明细对象
						BizBuyingRequisitionDetail bizBuyingRequisitionDetail = bizBuyingRequisitionDetailService.get(buyingDetailId);
						if(bizBuyingRequisitionDetail != null){
							//已提交采购单明细总采购数
							Integer submitOutExpertAmount = bizBuyingRequisitionDetail.getSubmitOutExpertAmount();
							//当前请购明细的请购数
							Integer buyExpertAmount = bizBuyingRequisitionDetail.getExpertAmount();
							//当前采购单明细采购数
							Integer purExpertAmount = Integer.valueOf(bizPurchaseDetail.getExpertAmount());
							//计算当前采购数和已提交数的和
							Integer sum = purExpertAmount+submitOutExpertAmount;
							if(sum > buyExpertAmount){
								//不可以提交  提示msg ++
								isCanSubmit = false;
								msg.append(bizPurchaseDetail.getGoodsName()+"采购数超出总请购数;");
							}
						}
					}
				}

				if(isCanSubmit){
					//可以提交
					for (BizPurchaseDetail bizPurchaseDetail : purchaseDetailList) {
						//根据采购单明细的请购明细id获取该请购明细的请购数和已提交采购数
						if(bizPurchaseDetail != null && StringUtils.isNotEmpty(bizPurchaseDetail.getPurchaseDetailId())){
							String buyingDetailId = bizPurchaseDetail.getBuyingDetailId();
							//获取对应请购明细对象
							BizBuyingRequisitionDetail bizBuyingRequisitionDetail = bizBuyingRequisitionDetailService.get(buyingDetailId);
							if(bizBuyingRequisitionDetail != null){
								//已提交采购单明细总采购数
								Integer submitOutExpertAmount = bizBuyingRequisitionDetail.getSubmitOutExpertAmount();
								//当前请购明细的请购数
								Integer buyExpertAmount = bizBuyingRequisitionDetail.getExpertAmount();
								//当前采购单明细采购数
								Integer purExpertAmount = Integer.valueOf(bizPurchaseDetail.getExpertAmount());
								//计算当前采购数和已提交数的和
								Integer sum = purExpertAmount+submitOutExpertAmount;
								//将本次提交采购数累加到请购明细的已提交采购总数
								bizBuyingRequisitionDetail.setSubmitOutExpertAmount(sum);
								bizBuyingRequisitionDetailService.update(bizBuyingRequisitionDetail);
							}
						}
					}

					//分单
					List<String> suppilerIds = bizPurchaseDetailService.selectByParIdGroupBySuppiler(purchase.getPurchaseId());
					if(suppilerIds != null && suppilerIds.size() > 1){	//采购单中2种或以上的供应商时才分单
						for (String suppilerId : suppilerIds) {
							//根据供应商分采购明细
							List<BizPurchaseDetail> purListi = new ArrayList<>();
							if(purchaseDetailList != null && purchaseDetailList.size() > 0){
								for (BizPurchaseDetail bizPurchaseDetail : purchaseDetailList) {
									if(bizPurchaseDetail != null && suppilerId.equals(bizPurchaseDetail.getSupplierId())){
										purListi.add(bizPurchaseDetail);
									}
								}
							}
							if(purListi != null && purListi.size() > 0){
								BizPurchase bizPurchasei = new BizPurchase();
								Double totalPrice = 0.0;	//重新计算采购总额
								//创建采购单
								try {
									BeanUtils.copyProperties(bizPurchasei,purchase);	//copy主采购单的属性到分单中
									bizPurchasei.setPurchaseId(IdGen.getUniqueKey());	//重新设置ID
									String purchaseAutoCode = AutoNameUtils.createAutoNameByTableName("biz_purchase");
									bizPurchasei.setPurchaseCode(purchaseAutoCode);	//重新设置编码
									bizPurchasei.setAuditStatus("20");	//设置分单为待审核状态

									for (BizPurchaseDetail bizPurchaseDetaii : purListi) {
										bizPurchaseDetaii.setPurchaseId(bizPurchasei.getPurchaseId());
										bizPurchaseDetailService.update(bizPurchaseDetaii);
										totalPrice += Double.valueOf(bizPurchaseDetaii.getTotalPrice());
									}
									bizPurchasei.setTotalPrice(totalPrice);
									bizPurchaseLogService.addBizPurchaseLog("分单新增",bizPurchasei.getPurchaseId());
									//保存分单
									bizPurchaseService.insert(bizPurchasei);

								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}
						//添加操作日志
						bizPurchaseLogService.addBizPurchaseLog("分单",purchase.getPurchaseId());
						bizPurchaseService.delete(purchase);	//主单逻辑删除
					}

				}else{
					msg.append("请认真核对采购数量!");
					addMessage(redirectAttributes, msg.toString());
					return "redirect:"+Global.getAdminPath()+"/biz/bizPurchase/list";
				}
			}


			//撤回和驳回 将请购明细的出库总数修改
			if("10".equals(bizPurchase.getAuditStatus()) || "40".equals(bizPurchase.getAuditStatus())){
				//提交采购单时校验数量
				for (BizPurchaseDetail bizPurchaseDetail : purchaseDetailList) {
					//根据采购单明细的请购明细id获取该请购明细的请购数和已提交采购数
					if (bizPurchaseDetail != null && StringUtils.isNotEmpty(bizPurchaseDetail.getPurchaseDetailId())) {
						String buyingDetailId = bizPurchaseDetail.getBuyingDetailId();
						//获取对应请购明细对象
						BizBuyingRequisitionDetail bizBuyingRequisitionDetail = bizBuyingRequisitionDetailService.get(buyingDetailId);
						if (bizBuyingRequisitionDetail != null) {
							//已提交采购单明细总采购数
							Integer submitOutExpertAmount = bizBuyingRequisitionDetail.getSubmitOutExpertAmount();
							//当前采购单明细采购数
							Integer purExpertAmount = Integer.valueOf(bizPurchaseDetail.getExpertAmount());
							//将本次提交采购数累加到请购明细的已提交采购总数
							bizBuyingRequisitionDetail.setSubmitOutExpertAmount(submitOutExpertAmount-purExpertAmount);
							bizBuyingRequisitionDetailService.update(bizBuyingRequisitionDetail);
						}
					}
				}
			}

			bizPurchaseService.updateAuditStatus(bizPurchase);
			addMessage(redirectAttributes, "操作成功");
		}else{
			addMessage(redirectAttributes, "操作失败");
		}
		return "redirect:"+Global.getAdminPath()+"/biz/bizPurchase/list";
	}
}